package com.dongjiantong.insurance.serviceImpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.model.Response;
import com.dongjiantong.common.utils.DateUtil;
import com.dongjiantong.insurance.mapper.InsuranceApplicationMapper;
import com.dongjiantong.insurance.model.InsuranceApplication;
import com.dongjiantong.insurance.service.InsuranceApplicationService;
import com.dongjiantong.mybatis.ServiceMybatis;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;

/**
 * 养殖保险 - 保单
 */
@Slf4j
@Service
public class InsuranceApplicationServiceImpl extends ServiceMybatis<InsuranceApplication> implements InsuranceApplicationService {
    @Resource
    private InsuranceApplicationMapper insuranceApplicationMapper;

    /**
     * 查询保单申请分页列表
     * @param farm_ids  养殖场id 集合(可为空,表示 查所有)
     * @param startDate 查询起始日期(可为空)
     * @param endDate   查询结束日期(可为空)
     * @param pageNum
     * @param pageSize
     * @return  Response<PageInfo<InsuranceApplication>>
     */
    @Override
    public Response<PageInfo<InsuranceApplication>> selectByExample(String farm_ids, String startDate, String endDate, Integer pageNum, Integer pageSize) {
        List<InsuranceApplication> insuranceApplicationList = null;
        try {
            PageHelper.startPage(pageNum,pageSize);

            Example example = new Example(InsuranceApplication.class);
            Example.Criteria criteria = example.createCriteria();
            if (!Strings.isNullOrEmpty(farm_ids)){
                String[] strings = farm_ids.split(",");
                List<String> idList = new ArrayList<String>();
                for (String farm_id : strings){
                    idList.add(farm_id);
                }
                criteria.andIn("farm_id",idList);
            }
            if (startDate != null){
                criteria.andGreaterThanOrEqualTo("create_at",DateUtil.stringToDate(startDate));
            }
            if (endDate != null){
                criteria.andLessThanOrEqualTo("create_at",DateUtil.stringToDate(endDate));
            }

            //查询,若criteria 的参数size为0则查所有,若不为0按条件查询
            insuranceApplicationList = insuranceApplicationMapper.selectByExample(example);
            return Response.ok(new PageInfo<InsuranceApplication>(insuranceApplicationList));
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR.getCode(),"查询发生异常,请稍后重试");
        }
    }

    @Override
    public List<InsuranceApplication> selectByArea(Map map) {
        return insuranceApplicationMapper.selectByArea(map);
    }
}
